package com.demo.friend.controller;

import com.demo.friend.client.UserClient;
import com.demo.friend.service.FriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2020/7/20.
 */
@RestController
@RequestMapping("/friend")
public class FriendController {

    @Autowired(required = false)
    private HttpServletRequest request;

    @Autowired
    private FriendService friendService;

    @Autowired
    private UserClient userClient;

    //添加好友或者非好友
    @RequestMapping(value = "/like/{friendid}/{type}",method = RequestMethod.PUT)
    public Result addFriend(@PathVariable String friendid,@PathVariable String type){
        //验证是否验证，拿到用户id
        Claims claims = (Claims)request.getAttribute("claims_user");
        if (claims == null){
            return new Result(false, StatusCode.LOGINERROR,"权限不足");
        }
        //得到用户id
        String userId = claims.getId();
        //判断添加好友，还是非好友
        if (type != null){
            if (type.equals("1")){
                int flag = friendService.add(userId,friendid);
                if (flag == 0){
                    return new Result(false, StatusCode.REPERROR,"不能重复添加好友");
                }
                if (flag == 1){
                    userClient.updateFansCountAndFoll(userId,friendid,1);
                    return new Result(true, StatusCode.OK,"添加成功");
                }
                //添加好友
            }else if (type.equals("2")){
                //添加非好友
               int flag = friendService.addNofriend(userId,friendid);
                if (flag == 0){
                    return new Result(false, StatusCode.REPERROR,"不能重复添加非好友");
                }
                if (flag == 1){
                    return new Result(true, StatusCode.OK,"添加成功");
                }
            }
            return new Result(false, StatusCode.ERROR,"参数异常");
        }else{
            return new Result(false, StatusCode.ERROR,"参数异常");
        }
    }


    //删除好友
    @RequestMapping(value = "/{friendid}",method = RequestMethod.DELETE)
    public Result deleteFriend(@PathVariable String friendid){
        //验证是否验证，拿到用户id
        Claims claims = (Claims)request.getAttribute("claims_user");
        if (claims == null){
            return new Result(false, StatusCode.LOGINERROR,"权限不足");
        }
        //得到用户id
        String userId = claims.getId();
        friendService.deleteFriend(userId,friendid);
        userClient.updateFansCountAndFoll( userId,friendid,-1);
        return new Result(true, StatusCode.OK,"删除成功");
    }
}
